package com.ai.flight.business.service.impl;

import java.time.LocalDate;
import java.util.List;

import com.ai.flight.business.data.Booking;
import com.ai.flight.business.data.BookingData;
import com.ai.flight.business.data.BookingStatus;
import com.ai.flight.business.record.FlightBooking;
import com.ai.flight.business.service.FlightService;
import org.springframework.stereotype.Service;

/**
 * @Author: suren@517na.com
 * @CreateTime: 2025-06-02
 * @Description: 航班业务实现类
 */

@Service
public class FlightServiceImpl implements FlightService {

    private static final BookingData db = BookingData.initData();


    @Override
    public List<FlightBooking.BookingDetails> getBookings() {
        return db.getBookings().stream().map(this::toBookingDetails).toList();
    }

    @Override
    public FlightBooking.BookingDetails getBookingDetails(String bookingNumber, String name) {
        var booking = this.findBooking(bookingNumber, name);
        return this.toBookingDetails(booking);
    }

    @Override
    public void changeBooking(String bookingNumber, String name, String newDate, String from, String to) {
        var booking = findBooking(bookingNumber, name);
        if (booking.getDate().isBefore(LocalDate.now().plusDays(1))) {
            //航班在24小时内不支持修改
            throw new IllegalArgumentException("Booking cannot bo changed within 24 hours of the start date.");
        }

        booking.setDate(LocalDate.parse(newDate));
        booking.setFrom(from);
        booking.setTo(to);
    }

    @Override
    public void cancelBooking(String bookingNumber, String name) {
        Booking booking = findBooking(bookingNumber, name);
        //航班24小时内不支持取消
        if (booking.getDate().isBefore(LocalDate.now().plusDays(2))) {
            throw new IllegalArgumentException("Booking cannot be cancelled within 48 hours of the start date.");
        }
        booking.setBookingStatus(BookingStatus.CANCELLED);
    }

    private Booking findBooking(String bookingNumber, String name) {
        return db.getBookings()
                .stream()
                .filter(b -> b.getBookingNumber().equalsIgnoreCase(bookingNumber))
                .filter(b -> b.getCustomer().getName().equalsIgnoreCase(name))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Booking not found"));
    }

    private FlightBooking.BookingDetails toBookingDetails(Booking booking) {
        return  new FlightBooking.BookingDetails(booking.getBookingNumber(), booking.getCustomer().getName(), booking.getDate(),
                booking.getBookingStatus(), booking.getFrom(), booking.getTo(), booking.getBookingClass().toString());
    }
}
